package com.hoolinks.app.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoolinks.app.org.service.IUserInfoService;
import com.hoolinks.domain.org.user.UserInfo;
import com.hoolinks.org.dto.clientobject.UserInfoVO;
import com.hoolinks.org.gatewayimpl.database.UserInfoMapper;
import com.hoolinks.org.gatewayimpl.database.dataobject.UserInfoPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  用户信息 服务实现类
 * </p>
 *
 * @author zzp
 * @since 2021-07-11
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfoPO> implements IUserInfoService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserInfoServiceValidator userInfoServiceValidator;

    @Override
    @Transactional
    public void save(UserInfoVO userInfoVO) {

        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVO, userInfo);
        // 校验
        userInfoServiceValidator.saveValidate(userInfo);

        UserInfoPO uiDO = null;

        if (userInfo.getId() != null) {
            // 查询已存在的用户信息
            UserInfoPO oldDO = this.getById(userInfo.getId());
            // 构造更新PO
            uiDO = UserInfoPO.updatePO(userInfo, oldDO);
        } else {
            // 构造新增PO
            uiDO = UserInfoPO.newPO(userInfo);
        }

        // 保存
        this.saveOrUpdate(uiDO);
    }

    @Override
    @Transactional
    public void delete(List<Integer> userIds) {

        // 校验
        userInfoServiceValidator.delValidate(userIds);

        // 删除
        this.removeByIds(userIds);
    }

    @Override
    @Transactional
    public void batchUpdateStatus(List<Integer> userIds, Integer status) {
        // 校验
        userInfoServiceValidator.updateStatusValidate(status);

        // 查询出用户列表
        LambdaQueryWrapper<UserInfoPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserInfoPO::getId, userIds);
        List<UserInfoPO> oldList = this.list(queryWrapper);

        List<UserInfoPO> newList = new ArrayList<>();

        oldList.forEach((userInfoDO)->{
            // 转换状态
            UserInfo userInfo = userInfoDO.toUserInfo().transformationStatus(status);
            newList.add(UserInfoPO.updatePO(userInfo, userInfoDO));
        });

        // 更新
        this.updateBatchById(newList);
    }
}
